package com.superb.common.database.interceptor;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.superb.common.core.enums.SuperbCode;
import com.superb.common.core.exception.SuperbException;
import com.superb.common.security.entity.SuperbTenant;
import com.superb.common.security.utils.SuperbUtils;
import com.superb.common.utils.AuthDataScopeUtils;
import com.superb.common.utils.HeardersUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import java.util.Set;

/**
 * 租户插件-租户拦截
 *
 * @Author: ajie
 * @CreateTime: 2024-05-08 15:52
 */
@Slf4j
@AllArgsConstructor
public class SuperbTenantInnerInterceptor implements TenantLineHandler {

    private final Set<String> ignoreTenantTable;
    private final String baseTenant;

    /**
     * 租户值
     *
     * @return
     */
    @Override
    public Expression getTenantId() {
        SuperbTenant tenantInfo = SuperbUtils.getTenantInfo();
        if (tenantInfo == null) {
            throw new SuperbException(SuperbCode.TENANT_NULL, "租户不存在！");
        }
        if (tenantInfo.getStatus() != 0) {
            throw new SuperbException(SuperbCode.TENANT_ENABLED, HeardersUtils.getTenantId() + "租户已禁用");
        }
        return new StringValue(HeardersUtils.getTenantId());
    }

    /**
     * 根据nacos根配置中的删除拦截表排除删除条件
     *
     * @param tableName
     * @return
     */
    @Override
    public boolean ignoreTable(String tableName) {
        // 如果租户id为配置id，那么则不需要租户隔离 如果存在排除租户注解，放行
        if (HeardersUtils.getTenantId().equals(baseTenant) || AuthDataScopeUtils.isTenant()) {
            return true;
        }
        return ignoreTenantTable.stream().anyMatch(table -> table.equals(tableName));
    }
}
